<?php


namespace app\admin\controller\system;

use app\admin\controller\BaseController;
use app\common\exception\MessageException;
use app\common\model\mysql\system\Department as DepartmentModel;
use app\common\validate\IDMustBePositiveInt;


class Department extends BaseController
{
    // 列表所有
    public function listTree()
    {
        $params = $this->request->param();
        $result = DepartmentModel::listTree($params);


        return $this->renderSuccess($result);
    }


    public function create()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不允许']);
        }
        $data = $this->request->param();
        // TODO 校验
        try {
            $findData = DepartmentModel::checkName($data['name']);
            if ($findData) {
                return $this->renderFail('部门已存在');
            }

            DepartmentModel::add($data);
            return $this->renderSuccess([], '添加成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function update()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }

        $params = $this->request->param();
        (new IDMustBePositiveInt())->goCheck();

        try {
            $findData = DepartmentModel::checkName($params['name'], $params['id']);
            if ($findData) {
                return $this->renderFail('部门已存在');
            }

            DepartmentModel::update($params);
            return $this->renderSuccess([], '更新成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function delete()
    {
        $params = $this->request->param();
        (new IDMustBePositiveInt())->goCheck();

        try {
            if ($params['id'] == DepartmentModel::$rootParent) {
                return $this->renderFail( '上层部门,暂不可删除');
            }
            $hasLower = DepartmentModel::where(['parent_id' => $params['id']])->findOrEmpty();

            if (!$hasLower->isEmpty()) {
                return $this->renderFail( '已关联下级部门,暂不可删除');
            }
            // 删除
            DepartmentModel::remove($params);
            return $this->renderSuccess([], '删除成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}